#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能童话书 - 最终版本
集成简化版ERNIE生成器，实现三次转折完整故事
"""

from flask import Flask, render_template, request, jsonify, send_from_directory
import os
import json
import random
import time
from datetime import datetime
from simple_ernie_generator import SimpleERNIEGenerator

app = Flask(__name__)
app.config['SECRET_KEY'] = 'storybook_secret_key_2024'

# 初始化简化版ERNIE生成器
ernie_generator = SimpleERNIEGenerator()

# 故事数据存储
stories_data = []

# 主题配置
THEMES = {
    "adventure": {
        "name": "冒险探索",
        "description": "勇敢的冒险和神奇的发现",
        "icon": "🗺️",
        "color": "#FF6B6B"
    },
    "friendship": {
        "name": "友谊成长", 
        "description": "温暖的友谊和真挚的情感",
        "icon": "👫",
        "color": "#4ECDC4"
    },
    "growth": {
        "name": "成长蜕变",
        "description": "个人成长和智慧获得",
        "icon": "🌱",
        "color": "#45B7D1"
    },
    "magic": {
        "name": "魔法奇幻",
        "description": "神奇的魔法和奇幻世界",
        "icon": "✨",
        "color": "#96CEB4"
    }
}

@app.route('/')
def index():
    """主页"""
    return render_template('index_final.html', themes=THEMES)

@app.route('/generate_story', methods=['POST'])
def generate_story():
    """生成故事API"""
    try:
        data = request.get_json()
        
        # 获取参数
        theme = data.get('theme', 'adventure')
        character_name = data.get('character_name', '').strip()
        user_prompt = data.get('user_prompt', '').strip()
        
        # 验证主题
        if theme not in THEMES and theme != 'magic':
            theme = 'adventure'
        
        # 处理魔法主题（映射到现有模板）
        if theme == 'magic':
            theme = random.choice(['adventure', 'friendship', 'growth'])
        
        print(f"🎭 开始生成故事 - 主题: {theme}, 角色: {character_name}")
        
        # 使用简化版ERNIE生成器生成故事
        story_content = ernie_generator.generate_story(theme, character_name)
        
        # 生成故事元数据
        story_id = f"story_{int(time.time())}_{random.randint(1000, 9999)}"
        
        story_data = {
            "id": story_id,
            "title": f"{character_name or '小主角'}的{THEMES.get(theme, THEMES['adventure'])['name']}",
            "content": story_content,
            "theme": theme,
            "character": character_name or "小主角",
            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "word_count": len(story_content),
            "reading_time": max(1, len(story_content) // 200)  # 估算阅读时间
        }
        
        # 保存故事
        stories_data.append(story_data)
        
        print(f"✅ 故事生成成功 - ID: {story_id}, 字数: {story_data['word_count']}")
        
        return jsonify({
            "success": True,
            "story": story_data,
            "message": "故事生成成功！这是一个包含三次转折的完整故事。"
        })
        
    except Exception as e:
        print(f"❌ 故事生成失败: {str(e)}")
        return jsonify({
            "success": False,
            "error": f"故事生成失败: {str(e)}",
            "message": "抱歉，故事生成遇到了问题，请稍后再试。"
        }), 500

@app.route('/get_stories')
def get_stories():
    """获取所有故事"""
    try:
        return jsonify({
            "success": True,
            "stories": stories_data[-10:],  # 返回最新的10个故事
            "total": len(stories_data)
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route('/get_story/<story_id>')
def get_story(story_id):
    """获取特定故事"""
    try:
        story = next((s for s in stories_data if s['id'] == story_id), None)
        if story:
            return jsonify({
                "success": True,
                "story": story
            })
        else:
            return jsonify({
                "success": False,
                "error": "故事未找到"
            }), 404
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route('/api/system_status')
def system_status():
    """系统状态API"""
    return jsonify({
        "status": "running",
        "model": "SimpleERNIE-Generator",
        "version": "1.0.0",
        "stories_count": len(stories_data),
        "uptime": "正常运行",
        "features": [
            "三次转折故事结构",
            "多主题故事生成", 
            "智能角色创建",
            "完整故事情节"
        ]
    })

@app.route('/static/<path:filename>')
def static_files(filename):
    """静态文件服务"""
    return send_from_directory('static', filename)

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return render_template('index_final.html', themes=THEMES), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({
        "success": False,
        "error": "服务器内部错误",
        "message": "抱歉，服务遇到了问题，请稍后再试。"
    }), 500

if __name__ == '__main__':
    print("=" * 60)
    print("🎭 智能童话书 - 最终版本")
    print("📚 集成简化版ERNIE生成器")
    print("🔄 支持三次转折完整故事生成")
    print("=" * 60)
    
    # 确保模板和静态文件目录存在
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static/css', exist_ok=True)
    os.makedirs('static/js', exist_ok=True)
    
    print("✅ 应用初始化完成！")
    print("🌐 访问地址: http://localhost:5002")
    print("📖 开始您的智能童话创作之旅！")
    print("=" * 60)
    
    # 启动应用
    app.run(host='0.0.0.0', port=5002, debug=True)